﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using General.Entities.ViewData.Admin;
using Microsoft.EntityFrameworkCore;

namespace General.Services.Admin
{
    public class AdminService:IAdminService
    {
        private readonly IRepository<tc_admin> tc_AdminRepository;
        private readonly IRepository<tc_role> tc_RoleRepository;
        private readonly IRepository<tc_departmentaccount> tc_DepartmentaccountRepository;

        public AdminService(IRepository<tc_admin> tc_adminRepository,
            IRepository<tc_role> tc_roleRepository,
            IRepository<tc_departmentaccount> tc_departmentaccountRepository)
        {
            tc_AdminRepository = tc_adminRepository;
            tc_RoleRepository = tc_roleRepository;
            tc_DepartmentaccountRepository = tc_departmentaccountRepository;
        }

        /// <summary>
        /// 根据编号获取用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<tc_admin> GetInfoById(int id)
        {
            var model = await tc_AdminRepository.GetAsync(x=>x.id==id);
            return model;
        }

        /// <summary>
        /// 根据用户名获取用户信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<tc_admin> GetInfoByUserName(string name)
        {
            var model = await tc_AdminRepository.GetAsync(x=>x.username == name);
            return model;
        }

        /// <summary>
        /// 更新登录时间信息
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public async Task UpdateLoginStatusInfo(int uid,string ip)
        {
            var user = await tc_AdminRepository.getByIdAsync(uid);

            user.lastip = ip;
            user.lasttime = DateTime.Now;
            await tc_AdminRepository.UpdateAsync(user);
        }

        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="headimg"></param>
        /// <returns></returns>
        public async Task UpdateHeadImg(int uid, string headimg)
        {
            var user = await tc_AdminRepository.getByIdAsync(uid);
            user.headimg = headimg;

            await tc_AdminRepository.UpdateAsync(user);
        }

        /// <summary>
        /// 修改用户名称
        /// </summary>
        /// <returns></returns>
        public async Task UpdateUsername(tc_admin model, string username)
        {
            model.nickname = username;

            await tc_AdminRepository.UpdateAsync(model);
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public async Task UpdateUserPwd(int uid, string pwd)
        {
            var user = await tc_AdminRepository.getByIdAsync(uid);
            user.password = EncryptHelper.Md5(pwd);

            await tc_AdminRepository.UpdateAsync(user);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="username"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public async Task<AdminResult> GetList(int page, int limit, string username, int status=-1,int organizationId=-1)
        {
            AdminResult result = new AdminResult();
            IQueryable<AdminModel> query;
            if (organizationId != -1)
            {
                query = from o in tc_DepartmentaccountRepository.Table.Where(x=>x.departmentId== organizationId)
                        join d in tc_AdminRepository.Table on o.uid equals d.id
                        where !string.IsNullOrWhiteSpace(username) ? d.username.Contains(username) : o.id >= 0
                        orderby o.id descending
                        select new AdminModel()
                        {
                            id = o.id,
                            createtime = d.createtime,
                            username = d.username,
                            headimg = d.headimg,
                            lastip = d.lastip,
                            lasttime = d.lasttime,
                            role = d.role,
                            status = d.status,
                            roles = new List<tc_role>(),
                            nickname = d.nickname
                        };
            }
            else
            {
                query = from d in tc_AdminRepository.Table
                        where !string.IsNullOrWhiteSpace(username) ? d.username.Contains(username) : d.id >= 0
                        orderby d.id descending
                        select new AdminModel()
                        {
                            id = d.id,
                            createtime = d.createtime,
                            username = d.username,
                            headimg = d.headimg,
                            lastip = d.lastip,
                            lasttime = d.lasttime,
                            role = d.role,
                            status = d.status,
                            roles = new List<tc_role>(),
                            nickname = d.nickname
                        };
            }
           
            if (status!=-1)
            {
                query = query.Where(x=>x.status == status);
            }
            result.count = await query.CountAsync();
            //获取所有角色列表
            var rolelist = await tc_RoleRepository.GetAllAsync().OrderBy(x=>x.id).ToListAsync();
            var list = await query.Skip((page - 1) * limit).Take(limit).ToListAsync();
            foreach (var item in list)
            {
                item.thumbnailPath = Core.Common.Thumbnail.ThumbnailHelper.GetThumbnailPath(item.headimg);
                if (string.IsNullOrEmpty(item.role))
                {
                    continue;
                }
                var rolearr = item.role.Split(",",StringSplitOptions.RemoveEmptyEntries).Select<string, int>(x => Convert.ToInt32(x));
                item.roles = rolelist.Where(x=>rolearr.Contains(x.id)).ToList();
            }
            result.data = list;
            result.code = 0;
            return result;
        }


        /// <summary>
        /// 增加用户
        /// </summary>
        /// <param name="username"></param>
        /// <param name="status"></param>
        /// <param name="role"></param>
        /// <returns></returns>
        public async Task<int> AddInfo(string username, int status, string role)
        {
            var model = new tc_admin()
            {
                 createtime = DateTime.Now, headimg = "/images/user.png", lastip = "", lasttime = DateTime.Now,
                  password = EncryptHelper.Md5("123456"), role = role, status = status, username = username,nickname = username , qqOpenId = "", wechatOpenId = ""
            };
            return await tc_AdminRepository.insertAsync(model);
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <returns></returns>
        public async Task EditInfo(tc_admin data)
        {
            var model = await tc_AdminRepository.getByIdAsync(data.id);
            model.headimg = data.headimg;
            model.role = data.role;
            model.username = data.username;
            model.nickname = data.nickname;
            model.status = data.status;
            await tc_AdminRepository.UpdateAsync(model);
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <returns></returns>
        public async Task<int> DeleteInfo(string ids)
        {
            var arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries);
            var arrints = arr.Select<string, int>(x => Convert.ToInt32(x));
            var list = await tc_AdminRepository.GetAllAsync(x => arrints.Contains(x.id)).ToListAsync();
            return await tc_AdminRepository.DeleteListAsync(list);
        }

        /// <summary>
        /// 编辑用户状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> EditStatus(int id,int status)
        {
            var user = await tc_AdminRepository.getByIdAsync(id);
            user.status = status;
            return await tc_AdminRepository.UpdateAsync(user);
        }

        /// <summary>
        /// 根据时间获取会员数量
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public async Task<int> GetCountByDate(DateTime? date)
        {
            if (date == null)
            {
                return await tc_AdminRepository.CountAsync();
            }
            return await tc_AdminRepository.Table.Where(x=>x.createtime >= date).CountAsync();
        }

        /// <summary>
        /// 根据openid获取用户的id
        /// </summary>
        /// <param name="type"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public async Task<int> GetIdByOpenId(string type, string openid)
        {
            int uid = -1;
            if (type == "wechat")
            {
                var res = await tc_AdminRepository.Table.Where(x => x.wechatOpenId == openid).Select(x => new tc_admin() { id = x.id, wechatOpenId = x.wechatOpenId }).FirstOrDefaultAsync();
                if (res!=null)
                {
                    uid = res.id;
                }
            }
            else if (type == "qq")
            {
                var res = await tc_AdminRepository.Table.Where(x => x.qqOpenId == openid).Select(x => new tc_admin() { id = x.id, wechatOpenId = x.wechatOpenId }).FirstOrDefaultAsync();
                if (res != null)
                {
                    uid = res.id;
                }
            }
                return uid;
        }

        /// <summary>
        /// 绑定第三方登录Openid
        /// </summary>
        /// <returns></returns>
        public async Task BindOpenId(int uid, string type, string openid)
        {
            if (type== "wechat")
            {
                tc_admin model = new tc_admin();
                model.id = uid;
                model.wechatOpenId = openid;
                Expression<Func<tc_admin, object>>[] updatedProperties = {
                    p => p.wechatOpenId
                };
                await tc_AdminRepository.UpdateByFieldsAsync(model, updatedProperties);
            }
            else if (type == "qq")
            {
                tc_admin model = new tc_admin() { id = uid };
                model.id = uid;
                model.qqOpenId = openid;
                Expression<Func<tc_admin, object>>[] updatedProperties = {
                    p => p.qqOpenId
                };
                await tc_AdminRepository.UpdateByFieldsAsync(model, updatedProperties);
            }
        }

        /// <summary>
        /// 判断是否已经绑定过openid
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> IsHasOpenid(string type, string openid, int? uid = null)
        {
            switch (type)
            {
                case "wechat":
                    if (uid == null)
                    {
                        return await tc_AdminRepository.IsExistAsync(x => x.wechatOpenId == openid);
                    }
                    else
                    {
                        var model = await tc_AdminRepository.GetAsync(x => x.id == uid);
                        return await tc_AdminRepository.IsExistAsync(x => x.wechatOpenId != model.wechatOpenId && x.wechatOpenId == openid);
                    }
                    break;
                case "qq":
                    if (uid == null)
                    {
                        return await tc_AdminRepository.IsExistAsync(x => x.qqOpenId == openid);
                    }
                    else
                    {
                        var model = await tc_AdminRepository.GetAsync(x => x.id == uid);
                        return await tc_AdminRepository.IsExistAsync(x => x.qqOpenId != model.qqOpenId && x.qqOpenId == openid);
                    }
                    break;
            }
            return false;
        }
    }
}
